/* eslint-disable node/no-unpublished-import */
/* eslint-env node */
// This rollup script is run by the command:
// 'npm run build'

import path from 'path'
import { lstatSync, readdirSync } from 'fs'
import rimraf from 'rimraf'
import babel from '@rollup/plugin-babel'
import copy from 'rollup-plugin-copy'
import { nodeResolve } from '@rollup/plugin-node-resolve'
import commonjs from '@rollup/plugin-commonjs'
import nodePolyfills from 'rollup-plugin-node-polyfills'
import url from '@rollup/plugin-url' // for XML/SVG files
// eslint-disable-next-line node/no-extraneous-import
import html from 'rollup-plugin-html'


import dynamicImportVars from '@rollup/plugin-dynamic-import-vars'
import { terser } from 'rollup-plugin-terser'
// import progress from 'rollup-plugin-progress';
import filesize from 'rollup-plugin-filesize'

import replace from '@rollup/plugin-replace';

// utility function
const getDirectories = (source) => {

  const isDirectory = (dir) => {
    return lstatSync(dir).isDirectory()
  }
  return readdirSync(source).map((name) => path.join(source, name)).filter((i) => isDirectory(i))
}

// capture the list of files to build for extensions and ext-locales
const extensionDirs = getDirectories('src/editor/extensions')

// const dest = ['../ems-ui/emsui/public/static/editor']

const dest = ['../ems-ui-1.8/public/static/editor']

// remove existing distribution
rimraf('../ems-ui-1.8/public/static/editor', () => console.info('recreating dist'))

// config for svgedit core module
const config = [{
  input: ['src/editor/Editor.js'],
  // global:{
  //   'jquery': '$' //告诉rollup 全局变量$即是jquery
  // },
  output: [
    {
      format: 'es',
      inlineDynamicImports: true,
      sourcemap: false,
      file: `${dest}/Editor.js`
    }
  ],
  plugins: [
    copy({
      targets: [
        { src: 'src/editor/index.html',dest},
        { src: 'src/editor/images', dest },
        { src: 'src/editor/oldImg', dest },
        { src: 'src/editor/components/jgraduate/images', dest: dest.map((d) => `${d}/components/jgraduate`) },
        { src: 'src/editor/extensions/ext-shapes/shapelib', dest: dest.map((d) => `${d}/extensions/ext-shapes`) },
        { src: 'src/editor/jgraduate',dest},
        { src: 'src/editor/embedapi.html', dest },
        { src: 'src/editor/embedapi.js', dest },
        { src: 'src/editor/browser-not-supported.html', dest },
        { src: 'src/editor/browser-not-supported.js', dest },
        { src: 'src/editor/svgedit.css', dest },
        { src: 'src/editor/pictool.html', dest },
        { src: 'src/editor/sheet.html', dest },
        { src: 'src/editor/colorpicker.html', dest },
        { src: 'src/editor/serveconfig.js', dest },
        { src: 'src/editor/flexble.js', dest }

      ]
    }),
    html({
      include: [
        'src/editor/panels/*.html',
        'src/editor/templates/*.html',
        'src/editor/dialogs/*.html'
      ]
    }),
    nodeResolve({
      browser: true,
      preferBuiltins: false
    }),
    commonjs(),
    dynamicImportVars({ include: 'src/editor/locale.js' }),
    babel({ babelHelpers: 'bundled', exclude: [/\/core-js\//] }), // exclude core-js to avoid circular dependencies.
    nodePolyfills(),
    terser({ keep_fnames: true }), // keep_fnames is needed to avoid an error when calling extensions.
    filesize(),
    replace({
      'process.env.NODE_ENV': JSON.stringify('production'),
      __buildDate__: () => JSON.stringify(new Date()),
      __buildVersion: 15
    })
  ]
},{
  input: ['src/editor/svgshow/svgshow.js'],
  // global:{
  //   'jquery': '$' //告诉rollup 全局变量$即是jquery
  // },
  output: [
    {
      // format: 'es',
      inlineDynamicImports: true,
      sourcemap: true,
      file: `${dest}/svgshow/svgshow.js`
    },

  ],
  plugins: [
    copy({
      targets: [
        { src: 'src/editor/svg.html',dest},
        { src: 'src/editor/svg_display.html',dest},
        { src: 'src/editor/svgshow/music/*', dest: dest.map((d) => `${d}/svgshow/music`)},
        { src: 'src/editor/svgshow/websocketworker.js', dest: dest.map((d) => `${d}/svgshow`)},
      ]
    }),
    html({
      include: [
        'src/editor/svgshow/*.html',
      ]
    }),
    nodeResolve({
      browser: true,
      preferBuiltins: false
    }),
    commonjs(),
    dynamicImportVars({ include: 'src/editor/locale.js' }),
    babel({ babelHelpers: 'bundled', exclude: [/\/core-js\//] }), // exclude core-js to avoid circular dependencies.
    nodePolyfills(),
    terser({ keep_fnames: true }), // keep_fnames is needed to avoid an error when calling extensions.
    filesize()
  ]
},{
  input:['src/editor/svgshow/svgshow_display.js'],
  output:[
    {
      // format: 'es',
      inlineDynamicImports: true,
     
      file: `${dest}/svgshow/svgshow_display.js`
    }
  ],
  plugins: [
    html({
      include: [
        'src/editor/svgshow/*.html',
      ]
    }),
    nodeResolve({
      browser: true,
      preferBuiltins: false
    }),
    commonjs(),
    dynamicImportVars({ include: 'src/editor/locale.js' }),
    babel({ babelHelpers: 'bundled', exclude: [/\/core-js\//] }), // exclude core-js to avoid circular dependencies.
    nodePolyfills(),
    terser({ keep_fnames: true }), // keep_fnames is needed to avoid an error when calling extensions.
    filesize()
  ]
}]

// config for dynamic extensions
extensionDirs.forEach((extensionDir) => {
  const extensionName = path.basename(extensionDir)
  extensionName && config.push(
    {
      input: `./src/editor/extensions/${extensionName}/${extensionName}.js`,
      output: [
        {
          // format: 'es',
          dir: `${dest}/extensions/${extensionName}`,
          inlineDynamicImports: true,
          sourcemap: false
        }
      ],
      plugins: [
        url({
          include: ['**/*.svg', '**/*.xml'],
          limit: 0,
          fileName: '[name][extname]'
        }),
        html({
          include: [
            'src/editor/extensions/*/*.html'
          ]
        }),
        nodeResolve({
          browser: true,
          preferBuiltins: true
        }),
        commonjs({ exclude: `src/editor/extensions/${extensionName}/${extensionName}.js` }),
        dynamicImportVars({ include: `src/editor/extensions/${extensionName}/${extensionName}.js` }),
        babel({ babelHelpers: 'bundled', exclude: [/\/core-js\//] }),
        nodePolyfills(),
        terser({ keep_fnames: true })
      ]
    }
  )
})

export default config
